package com.springboot.pratice.common.config.mthread;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zengjinliang
 * Create on 2021/12/7 16:35
 */
public class MThreadPoolExecutor extends ThreadPoolExecutor {

    private String poolName;
    private String fingerprint;

    /**
     * 构建线程池对象
     * @param poolName 线程程名称
     * @param corePoolSize 核心线程数
     * @param maximumPoolSize 最大线程数
     * @param keepAliveTime 线程空闲时间(单位：毫秒)
     * @param allWaitSize 最大排队任务数
     */
    public MThreadPoolExecutor(String poolName,int corePoolSize,
                               int maximumPoolSize,
                               long keepAliveTime,int allWaitSize) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(allWaitSize),
                Executors.defaultThreadFactory(),new AbortPolicy());
        this.poolName = poolName;
        this.fingerprint = calFingerprint(poolName,corePoolSize,maximumPoolSize,keepAliveTime,allWaitSize);
    }

    /**
     * 线程池对象指纹(特征)计算
     * @param poolName
     * @param corePoolSize
     * @param maximumPoolSize
     * @param keepAliveTime
     * @param allWaitSize
     * @return
     */
    public static String calFingerprint(String poolName,int corePoolSize,
                                 int maximumPoolSize,
                                 long keepAliveTime,int allWaitSize){
        return Joiner.on("@").join(poolName,corePoolSize,maximumPoolSize,keepAliveTime,allWaitSize).toString();
    }

    public String fingerprint(){
        return this.fingerprint;
    }

    public Map getState(){
        Map<String,Object> state = Maps.newHashMap();
        state.put("name",poolName);
        state.put("corePoolSize",getCorePoolSize());
        state.put("maximumPoolSize",getMaximumPoolSize());
        state.put("activeCount",getActiveCount());
        state.put("taskQueue",getQueue().size());
        return state;
    }
}
